﻿using CCSSolderUI.Common.Domain;
using CCSSolderUI.Common.Event;
using CCSSolderUI.Models;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CCSSolderUI.ViewModels.Dialogs
{
    public class JobConfigDialogViewModel : BindableBase, IDialogAware
    {
        #region 导航
        public string Title => "作业配置";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            partNumber = parameters.GetValue<string>("PartNumber");
            LoadParam();
            UpdateDataGrid1(partNumber);
            UpdateButtonList1(partNumber);
            UpdateDataGrid2(partNumber);
            UpdateButtonList2(partNumber);
        }
        #endregion
        #region 变量
        private readonly IDialogService dialogService;
        string partNumber = "";
        CancellationTokenSource source;
        IEventAggregator _eventAggregator;
        Param param;
        #endregion
        #region 属性
        private ObservableCollection<WorkPointDisp> pointList1 = new ObservableCollection<WorkPointDisp>();
        public ObservableCollection<WorkPointDisp> PointList1
        {
            get { return pointList1; }
            set { SetProperty(ref pointList1, value); }
        }
        private ObservableCollection<DispButton> buttonList1 = new ObservableCollection<DispButton>();
        public ObservableCollection<DispButton> ButtonList1
        {
            get { return buttonList1; }
            set { SetProperty(ref buttonList1, value); }
        }
        private ObservableCollection<WorkPointDisp> pointList2 = new ObservableCollection<WorkPointDisp>();
        public ObservableCollection<WorkPointDisp> PointList2
        {
            get { return pointList2; }
            set { SetProperty(ref pointList2, value); }
        }
        private ObservableCollection<DispButton> buttonList2 = new ObservableCollection<DispButton>();
        public ObservableCollection<DispButton> ButtonList2
        {
            get { return buttonList2; }
            set { SetProperty(ref buttonList2, value); }
        }
        private int pointList1SelectedIndex;
        public int PointList1SelectedIndex
        {
            get { return pointList1SelectedIndex; }
            set { SetProperty(ref pointList1SelectedIndex, value); }
        }
        private int pointList2SelectedIndex;
        public int PointList2SelectedIndex
        {
            get { return pointList2SelectedIndex; }
            set { SetProperty(ref pointList2SelectedIndex, value); }
        }
        private bool isAxisBusy;
        public bool IsAxisBusy
        {
            get { return isAxisBusy; }
            set { SetProperty(ref isAxisBusy, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand<object> dataGridSelectCommand1;
        public DelegateCommand<object> DataGridSelectCommand1 =>
            dataGridSelectCommand1 ?? (dataGridSelectCommand1 = new DelegateCommand<object>(ExecuteDataGridSelectCommand1));
        private DelegateCommand<object> dataGridSelectCommand2;
        public DelegateCommand<object> DataGridSelectCommand2 =>
            dataGridSelectCommand2 ?? (dataGridSelectCommand2 = new DelegateCommand<object>(ExecuteDataGridSelectCommand2));
        private DelegateCommand<object> dataGridCellEditEndingCommand1;
        public DelegateCommand<object> DataGridCellEditEndingCommand1 =>
            dataGridCellEditEndingCommand1 ?? (dataGridCellEditEndingCommand1 = new DelegateCommand<object>(ExecuteDataGridCellEditEndingCommand1));
        private DelegateCommand<object> dataGridCellEditEndingCommand2;
        public DelegateCommand<object> DataGridCellEditEndingCommand2 =>
            dataGridCellEditEndingCommand2 ?? (dataGridCellEditEndingCommand2 = new DelegateCommand<object>(ExecuteDataGridCellEditEndingCommand2));


        private DelegateCommand<object> isUseCheckCommand1;
        public DelegateCommand<object> IsUseCheckCommand1 =>
            isUseCheckCommand1 ?? (isUseCheckCommand1 = new DelegateCommand<object>(ExecuteIsUseCheckCommand1));
        private DelegateCommand<object> isUseCheckCommand2;
        public DelegateCommand<object> IsUseCheckCommand2 =>
            isUseCheckCommand2 ?? (isUseCheckCommand2 = new DelegateCommand<object>(ExecuteIsUseCheckCommand2));


        private DelegateCommand addPointCommand1;
        public DelegateCommand AddPointCommand1 =>
            addPointCommand1 ?? (addPointCommand1 = new DelegateCommand(ExecuteAddPointCommand1));
        private DelegateCommand<object> updatePointCommand1;
        public DelegateCommand<object> UpdatePointCommand1 =>
            updatePointCommand1 ?? (updatePointCommand1 = new DelegateCommand<object>(ExecuteUpdatePointCommand1));   
        private DelegateCommand addPointCommand2;
        public DelegateCommand AddPointCommand2 =>
            addPointCommand2 ?? (addPointCommand2 = new DelegateCommand(ExecuteAddPointCommand2));
        private DelegateCommand<object> updatePointCommand2;
        public DelegateCommand<object> UpdatePointCommand2 =>
            updatePointCommand2 ?? (updatePointCommand2 = new DelegateCommand<object>(ExecuteUpdatePointCommand2));
        private DelegateCommand<object> deletePointCommand1;
        public DelegateCommand<object> DeletePointCommand1 =>
            deletePointCommand1 ?? (deletePointCommand1 = new DelegateCommand<object>(ExecuteDeletePointCommand1));
        private DelegateCommand<object> deletePointCommand2;
        public DelegateCommand<object> DeletePointCommand2 =>
            deletePointCommand2 ?? (deletePointCommand2 = new DelegateCommand<object>(ExecuteDeletePointCommand2));
        private DelegateCommand<object> upShiftPointCommand1;
        public DelegateCommand<object> UpShiftPointCommand1 =>
            upShiftPointCommand1 ?? (upShiftPointCommand1 = new DelegateCommand<object>(ExecuteUpShiftPointCommand1));
        private DelegateCommand<object> upShiftPointCommand2;
        public DelegateCommand<object> UpShiftPointCommand2 =>
            upShiftPointCommand2 ?? (upShiftPointCommand2 = new DelegateCommand<object>(ExecuteUpShiftPointCommand2));
        private DelegateCommand<object> downShiftPointCommand1;
        public DelegateCommand<object> DownShiftPointCommand1 =>
            downShiftPointCommand1 ?? (downShiftPointCommand1 = new DelegateCommand<object>(ExecuteDownShiftPointCommand1));
        private DelegateCommand<object> downShiftPointCommand2;
        public DelegateCommand<object> DownShiftPointCommand2 =>
            downShiftPointCommand2 ?? (downShiftPointCommand2 = new DelegateCommand<object>(ExecuteDownShiftPointCommand2));
        private DelegateCommand<object> buttonCommand1;
        public DelegateCommand<object> ButtonCommand1 =>
            buttonCommand1 ?? (buttonCommand1 = new DelegateCommand<object>(ExecuteButtonCommand1));
        private DelegateCommand<object> buttonCommand2;
        public DelegateCommand<object> ButtonCommand2 =>
            buttonCommand2 ?? (buttonCommand2 = new DelegateCommand<object>(ExecuteButtonCommand2));
        private DelegateCommand<object> mouseDoubleClickCommand1;
        public DelegateCommand<object> MouseDoubleClickCommand1 =>
            mouseDoubleClickCommand1 ?? (mouseDoubleClickCommand1 = new DelegateCommand<object>(ExecuteMouseDoubleClickCommand1));
        private DelegateCommand<object> mouseDoubleClickCommand2;
        public DelegateCommand<object> MouseDoubleClickCommand2 =>
            mouseDoubleClickCommand2 ?? (mouseDoubleClickCommand2 = new DelegateCommand<object>(ExecuteMouseDoubleClickCommand2));

        async void ExecuteMouseDoubleClickCommand2(object obj)
        {
            int id = (int)obj;
            var point = PointList2.FirstOrDefault(t => t.Id == id);
            source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            if (point != null)
            {
                WorkPoint wp = new WorkPoint();
                wp.X = point.X;
                wp.Y = point.Y;
                wp.Z = point.Z;
                if (MessageBox.Show($"确认运动到{point.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsAxisBusy = true;
                    await Task.Run(() => GoActionXYZ(token, wp), token).ContinueWith(t => IsAxisBusy = false);
                    //await Task.Delay(10000).ContinueWith(t => IsAxisBusy = false);
                }
            }
        }
        async void ExecuteMouseDoubleClickCommand1(object obj)
        {
            int id = (int)obj;
            var point = PointList1.FirstOrDefault(t => t.Id == id);
            source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            if (point != null)
            {
                WorkPoint wp = new WorkPoint();
                wp.X = point.X;
                wp.Y = point.Y;
                wp.Z = point.Z;
                if (MessageBox.Show($"确认运动到{point.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsAxisBusy = true;
                    await Task.Run(() => GoActionXYZ(token, wp), token).ContinueWith(t => IsAxisBusy = false);
                    //await Task.Delay(10000).ContinueWith(t => IsAxisBusy = false);
                }
            }
        }
        void ExecuteButtonCommand1(object obj)
        {
            int id = (int)obj;
            for (int i = 0; i < PointList1.Count; i++)
            {
                if (PointList1[i].Id == id)
                {
                    PointList1SelectedIndex = i;
                    break;
                }
            }
        }
        void ExecuteButtonCommand2(object obj)
        {
            int id = (int)obj;
            for (int i = 0; i < PointList2.Count; i++)
            {
                if (PointList2[i].Id == id)
                {
                    PointList2SelectedIndex = i;
                    break;
                }
            }
        }
        void ExecuteUpdatePointCommand1(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                if (MessageBox.Show($"确认更新{wp.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    bool changed = false;
                    using (var db = new DTContext(partNumber))
                    {
                        var wpToUpdate = db.WorkPoints.FirstOrDefault(t => t.Hand == 0 && t.Id == wp.Id);
                        if (wpToUpdate != null)
                        {
                            wpToUpdate.X = Math.Round(GTSCard.Instance.GetEnc(GTSCard.Instance.X1), 3);
                            wpToUpdate.Y = Math.Round(GTSCard.Instance.GetEnc(GTSCard.Instance.Y1), 3);
                            wpToUpdate.Z = Math.Round(GTSCard.Instance.GetEnc(GTSCard.Instance.Z1), 3);
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                    if (changed)
                    {
                        UpdateDataGrid1(partNumber);
                        UpdateButtonList1(partNumber);
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteUpdatePointCommand2(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                if (MessageBox.Show($"确认更新{wp.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    bool changed = false;
                    using (var db = new DTContext(partNumber))
                    {
                        var wpToUpdate = db.WorkPoints.FirstOrDefault(t => t.Hand == 1 && t.Id == wp.Id);
                        if (wpToUpdate != null)
                        {
                            wpToUpdate.X = Math.Round(GTSCard.Instance.GetEnc(GTSCard.Instance.X1), 3);
                            wpToUpdate.Y = Math.Round(GTSCard.Instance.GetEnc(GTSCard.Instance.Y1), 3);
                            wpToUpdate.Z = Math.Round(GTSCard.Instance.GetEnc(GTSCard.Instance.Z1), 3);
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                    if (changed)
                    {
                        UpdateDataGrid2(partNumber);
                        UpdateButtonList2(partNumber);
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteDownShiftPointCommand1(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                bool changed = false;
                using (var db = new DTContext(partNumber))
                {
                    var curp = db.WorkPoints.FirstOrDefault(w => w.Hand == 0 && w.Id == wp.Id);
                    if (curp != null)
                    {
                        var wp1 = db.WorkPoints.Where(t => t.Hand == 0 && t.PcsOrder > wp.PcsOrder).OrderBy(t => t.PcsOrder).FirstOrDefault();
                        if (wp1 != null)
                        {
                            int box = wp1.PcsOrder;
                            int box1 = curp.PcsOrder;
                            wp1.PcsOrder = box1;
                            curp.PcsOrder = box;
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                }
                if (changed)
                {
                    var selectindex = PointList1SelectedIndex;
                    UpdateDataGrid1(partNumber);
                    CancelButtonList1();
                    if (selectindex < PointList1.Count - 1)
                    {
                        PointList1SelectedIndex = selectindex + 1;
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteDownShiftPointCommand2(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                bool changed = false;
                using (var db = new DTContext(partNumber))
                {
                    var curp = db.WorkPoints.FirstOrDefault(w => w.Hand == 1 && w.Id == wp.Id);
                    if (curp != null)
                    {
                        var wp1 = db.WorkPoints.Where(t => t.Hand == 1 && t.PcsOrder > wp.PcsOrder).OrderBy(t => t.PcsOrder).FirstOrDefault();
                        if (wp1 != null)
                        {
                            int box = wp1.PcsOrder;
                            int box1 = curp.PcsOrder;
                            wp1.PcsOrder = box1;
                            curp.PcsOrder = box;
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                }
                if (changed)
                {
                    var selectindex = PointList2SelectedIndex;
                    UpdateDataGrid2(partNumber);
                    CancelButtonList2();
                    if (selectindex < PointList2.Count - 1)
                    {
                        PointList2SelectedIndex = selectindex + 1;
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteUpShiftPointCommand1(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                bool changed = false;
                using (var db = new DTContext(partNumber))
                {
                    var curp = db.WorkPoints.FirstOrDefault(w => w.Hand == 0 && w.Id == wp.Id);
                    if (curp != null)
                    {
                        var wp1 = db.WorkPoints.Where(t => t.Hand == 0 && t.PcsOrder < wp.PcsOrder).OrderByDescending(t => t.PcsOrder).FirstOrDefault();
                        if (wp1 != null)
                        {
                            int box = wp1.PcsOrder;
                            int box1 = curp.PcsOrder;
                            wp1.PcsOrder = box1;
                            curp.PcsOrder = box;
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                }
                if (changed)
                {
                    var selectindex = PointList1SelectedIndex;
                    UpdateDataGrid1(partNumber);
                    CancelButtonList1();
                    if (selectindex > 0)
                    {
                        PointList1SelectedIndex = selectindex - 1;
                    }
                    
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteUpShiftPointCommand2(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                bool changed = false;
                using (var db = new DTContext(partNumber))
                {
                    var curp = db.WorkPoints.FirstOrDefault(w => w.Hand == 1 && w.Id == wp.Id);
                    if (curp != null)
                    {
                        var wp1 = db.WorkPoints.Where(t => t.Hand == 1 && t.PcsOrder < wp.PcsOrder).OrderByDescending(t => t.PcsOrder).FirstOrDefault();
                        if (wp1 != null)
                        {
                            int box = wp1.PcsOrder;
                            int box1 = curp.PcsOrder;
                            wp1.PcsOrder = box1;
                            curp.PcsOrder = box;
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                }
                if (changed)
                {
                    var selectindex = PointList2SelectedIndex;
                    UpdateDataGrid2(partNumber);
                    CancelButtonList2();
                    if (selectindex > 0)
                    {
                        PointList2SelectedIndex = selectindex - 1;
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteDeletePointCommand1(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                if (MessageBox.Show($"确认删除{wp.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    bool changed = false;
                    using (var db = new DTContext(partNumber))
                    {
                        var wpToDel = db.WorkPoints.FirstOrDefault(t => t.Hand == 0 && t.Id == wp.Id);
                        if (wpToDel != null)
                        {
                            db.WorkPoints.Remove(wpToDel);
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                    if (changed)
                    {
                        UpdateDataGrid1(partNumber);
                        UpdateButtonList1(partNumber);
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteDeletePointCommand2(object obj)
        {
            if (obj != null)
            {
                WorkPoint wp = (WorkPoint)obj;
                if (MessageBox.Show($"确认删除{wp.Name}吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    bool changed = false;
                    using (var db = new DTContext(partNumber))
                    {
                        var wpToDel = db.WorkPoints.FirstOrDefault(t => t.Hand == 1 && t.Id == wp.Id);
                        if (wpToDel != null)
                        {
                            db.WorkPoints.Remove(wpToDel);
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                    if (changed)
                    {
                        UpdateDataGrid2(partNumber);
                        UpdateButtonList2(partNumber);
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何点位", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteAddPointCommand1()
        {
            int count = 0;
            using (var db = new DTContext(partNumber))
            {
                count = db.WorkPoints.Where(w => w.Hand == 0).Count() + 1;
            }
            DialogParameters param = new DialogParameters();
            param.Add("Name", count.ToString());
            dialogService.ShowDialog("AddPointDialog", param,arg => 
            {
                if (arg.Result == ButtonResult.Yes)
                {
                    using (var db = new DTContext(partNumber))
                    {
                        int pcsorder = 0;
                        if (db.WorkPoints.Where(w => w.Hand == 0).Any())
                        {
                            pcsorder = db.WorkPoints.Where(w => w.Hand == 0).Max(t => t.PcsOrder);
                        }
                        db.WorkPoints.Add(new WorkPoint() 
                        {
                            Name = arg.Parameters.GetValue<string>("Name"),
                            X = arg.Parameters.GetValue<double>("X"),
                            Y = arg.Parameters.GetValue<double>("Y"),
                            Z = arg.Parameters.GetValue<double>("Z"),
                            ST_X = 0,
                            ST_Y = 0,
                            ST_H = 0,
                            Remark = arg.Parameters.GetValue<string>("Remark"),
                            PcsOrder = pcsorder + 1,
                            Hand = 0,
                            IsUse = true
                        });
                        db.SaveChanges();
                    }
                    UpdateDataGrid1(partNumber);
                    UpdateButtonList1(partNumber);
                }
            });
        }
        void ExecuteAddPointCommand2()
        {
            int count = 0;
            using (var db = new DTContext(partNumber))
            {
                count = db.WorkPoints.Where(w => w.Hand == 1).Count() + 1;
            }
            DialogParameters param = new DialogParameters();
            param.Add("Name", count.ToString());
            dialogService.ShowDialog("AddPointDialog", param, arg =>
            {
                if (arg.Result == ButtonResult.Yes)
                {
                    using (var db = new DTContext(partNumber))
                    {
                        int pcsorder = 0;
                        if (db.WorkPoints.Where(w => w.Hand == 1).Any())
                        {
                            pcsorder = db.WorkPoints.Where(w => w.Hand == 1).Max(t => t.PcsOrder);
                        }
                        db.WorkPoints.Add(new WorkPoint()
                        {
                            Name = arg.Parameters.GetValue<string>("Name"),
                            X = arg.Parameters.GetValue<double>("X"),
                            Y = arg.Parameters.GetValue<double>("Y"),
                            Z = arg.Parameters.GetValue<double>("Z"),
                            ST_X = 0,
                            ST_Y = 0,
                            ST_H = 0,
                            Remark = arg.Parameters.GetValue<string>("Remark"),
                            PcsOrder = pcsorder + 1,
                            Hand = 1,
                            IsUse = true
                        });
                        db.SaveChanges();
                    }
                    UpdateDataGrid2(partNumber);
                    UpdateButtonList2(partNumber);
                }
            });
        }
        void ExecuteIsUseCheckCommand1(object obj)
        {
            WorkPointDisp cwp = (WorkPointDisp)obj;
            using (var db = new DTContext(partNumber))
            {
                var wpoint = db.WorkPoints.FirstOrDefault(w => w.Id == cwp.Id && w.Hand == 0);
                if (wpoint != null)
                {
                    wpoint.IsUse = cwp.IsUse;
                    db.SaveChanges();
                }
            }
        }
        void ExecuteIsUseCheckCommand2(object obj)
        {
            WorkPointDisp cwp = (WorkPointDisp)obj;
            using (var db = new DTContext(partNumber))
            {
                var wpoint = db.WorkPoints.FirstOrDefault(w => w.Id == cwp.Id && w.Hand == 1);
                if (wpoint != null)
                {
                    wpoint.IsUse = cwp.IsUse;
                    db.SaveChanges();
                }
            }
        }
        void ExecuteDataGridCellEditEndingCommand1(object obj)
        {
            WorkPointDisp cwp = (WorkPointDisp)obj;
            using (var db = new DTContext(partNumber))
            {
                var wpoint = db.WorkPoints.FirstOrDefault(w => w.Id == cwp.Id && w.Hand == 0);
                if (wpoint != null)
                {
                    wpoint.Name = cwp.Name;
                    wpoint.X = cwp.X;
                    wpoint.Y = cwp.Y;
                    wpoint.Z = cwp.Z;
                    wpoint.ST_X = cwp.ST_X;
                    wpoint.ST_Y = cwp.ST_Y;
                    wpoint.ST_H = cwp.ST_H;
                    wpoint.BarIndex = cwp.BarIndex;
                    wpoint.Remark = cwp.Remark;
                    db.SaveChanges();
                }
            }
            var button = ButtonList1.FirstOrDefault(t => t.Id == cwp.Id);
            if (button != null)
            {
                button.Name = cwp.Name;
                button.Left = (int)(cwp.X / 1800 * 560);
                button.Bottom = (int)(cwp.Y / 800 * 560);
            }
        }
        void ExecuteDataGridCellEditEndingCommand2(object obj)
        {
            WorkPointDisp cwp = (WorkPointDisp)obj;
            using (var db = new DTContext(partNumber))
            {
                var wpoint = db.WorkPoints.FirstOrDefault(w => w.Id == cwp.Id && w.Hand == 1);
                if (wpoint != null)
                {
                    wpoint.Name = cwp.Name;
                    wpoint.X = cwp.X;
                    wpoint.Y = cwp.Y;
                    wpoint.Z = cwp.Z;
                    wpoint.ST_X = cwp.ST_X;
                    wpoint.ST_Y = cwp.ST_Y;
                    wpoint.ST_H = cwp.ST_H;
                    wpoint.BarIndex = cwp.BarIndex;
                    wpoint.Remark = cwp.Remark;
                    db.SaveChanges();
                }
            }
            var button = ButtonList2.FirstOrDefault(t => t.Id == cwp.Id);
            if (button != null)
            {
                button.Name = cwp.Name;
                button.Left = (int)(cwp.X / 1800 * 560);
                button.Bottom = (int)(cwp.Y / 800 * 560);
            }
        }
        void ExecuteDataGridSelectCommand1(object obj)
        {
            if (obj != null)
            {
                WorkPointDisp wp = (WorkPointDisp)obj;
                CancelButtonList1();
                var button1 = ButtonList1.FirstOrDefault(t => t.Id == wp.Id);
                if (button1 != null)
                {
                    button1.Select = true;
                }
            }
        }
        void ExecuteDataGridSelectCommand2(object obj)
        {
            if (obj != null)
            {
                WorkPointDisp wp = (WorkPointDisp)obj;
                CancelButtonList2();
                var button1 = ButtonList2.FirstOrDefault(t => t.Id == wp.Id);
                if (button1 != null)
                {
                    button1.Select = true;
                }

            }
        }
        #endregion
        #region 构造函数
        public JobConfigDialogViewModel(DialogService _dialogService, IEventAggregator ea)
        {
            dialogService = _dialogService;
            _eventAggregator = ea;
            _eventAggregator.GetEvent<MessagePrintEvent>().Subscribe(MessageReceived);
            IsAxisBusy = false;
        }
        #endregion
        #region 功能函数
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, partNumber, "Param.json"));
                param = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                _eventAggregator.GetEvent<MessagePrintEvent>().Publish(new Common.Event.Message() { Sender = "AxisDialog", Type = "Print", Content = ex.Message });
            }
        }
        private void MessageReceived(Common.Event.Message obj)
        {
            switch (obj.Type)
            {
                case "Select":
                    partNumber = obj.Content;
                    LoadParam();
                    UpdateDataGrid1(partNumber);
                    UpdateButtonList1(partNumber);
                    break;
                default:
                    break;
            }
        }
        void UpdateDataGrid1(string partNumber)
        {
            PointList1.Clear();
            using (var db = new DTContext(partNumber))
            {
                var wpoints = db.WorkPoints.Where(p => p.Hand == 0).OrderBy(p => p.PcsOrder).ToList();
                if (wpoints.Any())
                {
                    for (int i = 0; i < wpoints.Count; i++)
                    {
                        PointList1.Add(
                            new WorkPointDisp()
                            {
                                Id = wpoints[i].Id,
                                Name = wpoints[i].Name,
                                X = wpoints[i].X,
                                Y = wpoints[i].Y,
                                Z = wpoints[i].Z,
                                ST_X = wpoints[i].ST_X,
                                ST_Y = wpoints[i].ST_Y,
                                ST_H = wpoints[i].ST_H,
                                BarIndex = wpoints[i].BarIndex,
                                Remark = wpoints[i].Remark,
                                IsUse = wpoints[i].IsUse,
                                PcsOrder = wpoints[i].PcsOrder,
                            }
                            );
                    }
                }
            }
        }
        void UpdateDataGrid2(string partNumber)
        {
            PointList2.Clear();
            using (var db = new DTContext(partNumber))
            {
                var wpoints = db.WorkPoints.Where(p => p.Hand == 1).OrderBy(p => p.PcsOrder).ToList();
                if (wpoints.Any())
                {
                    for (int i = 0; i < wpoints.Count; i++)
                    {
                        PointList2.Add(
                            new WorkPointDisp()
                            {
                                Id = wpoints[i].Id,
                                Name = wpoints[i].Name,
                                X = wpoints[i].X,
                                Y = wpoints[i].Y,
                                Z = wpoints[i].Z,
                                ST_X = wpoints[i].ST_X,
                                ST_Y = wpoints[i].ST_Y,
                                ST_H = wpoints[i].ST_H,
                                BarIndex = wpoints[i].BarIndex,
                                Remark = wpoints[i].Remark,
                                IsUse = wpoints[i].IsUse,
                                PcsOrder = wpoints[i].PcsOrder,
                            }
                            );
                    }
                }
            }
        }
        void UpdateButtonList1(string partNumber)
        {
            ButtonList1.Clear();
            using (var db = new DTContext(partNumber))
            {
                var wpoints = db.WorkPoints.Where(p => p.Hand == 0).OrderBy(p => p.PcsOrder).ToList();
                if (wpoints.Any())
                {
                    for (int i = 0; i < wpoints.Count; i++)
                    {
                        ButtonList1.Add(
                            new DispButton()
                            {
                                Id =wpoints[i].Id,
                                Width = 40,
                                Height = 40,
                                Select = false,
                                Name = wpoints[i].Name,
                                Left = (int)(wpoints[i].X / 1800 * 560),
                                Bottom = (int)(wpoints[i].Y / 800 * 560)
                            }
                            );
                    }
                }
            }
        }
        void UpdateButtonList2(string partNumber)
        {
            ButtonList2.Clear();
            using (var db = new DTContext(partNumber))
            {
                var wpoints = db.WorkPoints.Where(p => p.Hand == 1).OrderBy(p => p.PcsOrder).ToList();
                if (wpoints.Any())
                {
                    for (int i = 0; i < wpoints.Count; i++)
                    {
                        ButtonList2.Add(
                            new DispButton()
                            {
                                Id = wpoints[i].Id,
                                Width = 40,
                                Height = 40,
                                Select = false,
                                Name = wpoints[i].Name,
                                Left = (int)(wpoints[i].X / 1800 * 560),
                                Bottom = (int)(wpoints[i].Y / 800 * 560)
                            }
                            );
                    }
                }
            }
        }
        void CancelButtonList1()
        {
            for (int i = 0; i < ButtonList1.Count; i++)
            {
                ButtonList1[i].Select = false;
            }
        }
        void CancelButtonList2()
        {
            for (int i = 0; i < ButtonList2.Count; i++)
            {
                ButtonList2[i].Select = false;
            }
        }
        private void GoActionXYZ(CancellationToken token, WorkPoint point)
        {
            int stepnum = 0;
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                switch (stepnum)
                {
                    case 0:
                        GTSCard.Instance.AxisPosMove(ref GTSCard.Instance.X1, point.X,param.X1JogSpeed);
                        GTSCard.Instance.AxisPosMove(ref GTSCard.Instance.Y1, point.Y, param.Y1JogSpeed);
                        GTSCard.Instance.AxisPosMove(ref GTSCard.Instance.Z1, point.Z, param.Z1JogSpeed);
                        stepnum = 1;
                        break;
                    case 1:
                        if (GTSCard.Instance.AxisCheckDone(GTSCard.Instance.X1) && GTSCard.Instance.AxisCheckDone(GTSCard.Instance.Y1) && GTSCard.Instance.AxisCheckDone(GTSCard.Instance.Z1))
                        {
                            return;
                        }
                        break;
                    default:
                        break;
                }
                System.Threading.Thread.Sleep(100);
            }
        }
        #endregion
    }
    public class WorkPointDisp : WorkPoint, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
    }


    public class DispButton : INotifyPropertyChanged
    {
        public int Id { get; set; }
        private int left;
        public int Left
        {
            get { return left; }
            set
            {
                left = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Left"));
                }
            }
        }
        private int bottom;
        public int Bottom
        {
            get { return bottom; }
            set
            {
                bottom = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Bottom"));
                }
            }
        }
        public int Width { get; set; }
        public int Height { get; set; }
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }
        private bool select;
        public bool Select
        {
            get { return select; }
            set
            {
                select = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Select"));
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
    }

}
